<template>
  <div class="order-list">
    <div class="page-header">
      <h2>订单管理</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建订单
      </el-button>
    </div>
    
    
    <div class="filters">
      <el-select v-model="statusFilter" placeholder="按状态筛选" clearable @change="loadOrders">
        <el-option label="待确认" :value="1" />
        <el-option label="已确认" :value="2" />
        <el-option label="服务中" :value="3" />
        <el-option label="已完成" :value="4" />
        <el-option label="已取消" :value="5" />
      </el-select>
      <el-button @click="loadOrders">刷新</el-button>
    </div>
    
    <el-table :data="orders" style="width: 100%" v-loading="loading">
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column prop="orderNo" label="订单编号" width="150" />
      <el-table-column prop="serviceName" label="服务名称" />
      <el-table-column prop="userName" label="客户" />
      <el-table-column prop="amount" label="金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="下单时间" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="warning">待确认</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info">已确认</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="primary">服务中</el-tag>
          <el-tag v-else-if="scope.row.status === 4" type="success">已完成</el-tag>
          <el-tag v-else type="danger">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="viewOrder(scope.row)">查看</el-button>
          <el-button v-if="scope.row.status === 1" size="small" type="success" @click="confirmOrder(scope.row.orderId)">确认</el-button>
          <el-button v-if="scope.row.status === 2" size="small" type="primary" @click="startService(scope.row.orderId)">开始服务</el-button>
          <el-button v-if="scope.row.status === 3" size="small" type="warning" @click="completeOrder(scope.row.orderId)">完成</el-button>
          
          <el-button v-if="scope.row.status === 4 && (scope.row.reviewed === 0 || scope.row.reviewed === null || scope.row.reviewed === undefined)" 
                     size="small" type="primary" @click="reviewOrder(scope.row)">评价</el-button>
          <el-button v-if="scope.row.status === 4 && scope.row.reviewed === 1" 
                     size="small" type="info" disabled>已评价</el-button>
          <el-button v-if="scope.row.status < 3" size="small" type="danger" @click="cancelOrder(scope.row.orderId)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    
    <el-dialog v-model="showDetailDialog" title="订单详情" width="600px">
      <div v-if="selectedOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="服务名称">{{ selectedOrder.serviceName }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{ selectedOrder.userName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.phone }}</el-descriptions-item>
          <el-descriptions-item label="服务地址">{{ selectedOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="服务时间">{{ selectedOrder.serviceTime }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ selectedOrder.amount }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ selectedOrder.orderDate }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 20px;">
          <h4>服务要求：</h4>
          <p>{{ selectedOrder.remark || '无特殊要求' }}</p>
        </div>
      </div>
    </el-dialog>
    
    
    <el-dialog v-model="showReviewDialog" title="订单评价" width="500px">
      <div v-if="reviewOrderData">
        <div style="margin-bottom: 20px;">
          <h4>订单信息</h4>
          <p>订单号: {{ reviewOrderData.orderNo }}</p>
          <p>服务: {{ reviewOrderData.serviceName }}</p>
        </div>
        
        <el-form :model="reviewForm" label-width="80px">
          <el-form-item label="服务评分" required>
            <el-rate
              v-model="reviewForm.rating"
              :texts="['极差', '失望', '一般', '满意', '惊喜']"
              show-text
            />
          </el-form-item>
          <el-form-item label="评价内容">
            <el-input
              v-model="reviewForm.content"
              type="textarea"
              :rows="4"
              placeholder="请分享您的服务体验..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReview" :disabled="!reviewForm.rating">提交评价</el-button>
      </template>
    </el-dialog>

    
    <el-dialog v-model="showCreateDialog" title="创建订单" width="600px">
      <el-form :model="newOrder" label-width="100px">
        <el-form-item label="选择服务">
          <el-select v-model="newOrder.serviceId" placeholder="请选择服务">
            <el-option
              v-for="service in availableServices"
              :key="service.serviceId"
              :label="service.serviceName"
              :value="service.serviceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务地址">
          <el-input v-model="newOrder.address" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newOrder.phone" />
        </el-form-item>
        <el-form-item label="服务时间">
          <el-date-picker
            v-model="newOrder.serviceTime"
            type="datetime"
            placeholder="选择服务时间"
          />
        </el-form-item>
        <el-form-item label="特殊要求">
          <el-input v-model="newOrder.requirements" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createOrder">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'OrderList',
  data() {
    return {
      orders: [],
      loading: false,
      statusFilter: null,
      showDetailDialog: false,
      showCreateDialog: false,
      showReviewDialog: false,
      selectedOrder: null,
      reviewOrderData: null,
      availableServices: [],
      newOrder: {
        serviceId: null,
        address: '',
        phone: '',
        serviceTime: null,
        requirements: ''
      },
      reviewForm: {
        rating: 0,
        content: ''
      }
    }
  },
  mounted() {
    this.loadOrders()
    this.loadServices()
  },
  methods: {
    async loadOrders() {
      this.loading = true
      try {
        let url = '/api/orders'
        if (this.statusFilter) {
          url += `?status=${this.statusFilter}`
        }
        
        const response = await api.get(url)
        if (response.success) {
          this.orders = response.data
        } else {
          ElMessage.error('加载订单列表失败')
        }
      } catch (error) {
        ElMessage.error('加载订单列表失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadServices() {
      try {
        const response = await api.get('/api/services')
        if (response.success) {
          this.availableServices = response.data
        }
      } catch (error) {
      }
    },
    
    viewOrder(order) {
      this.selectedOrder = order
      this.showDetailDialog = true
    },
    
    async confirmOrder(orderId) {
      try {
        await ElMessageBox.confirm('确认接受此订单？', '确认操作', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api.put(`/api/orders/${orderId}/status`, { status: 2 })
        if (response.success) {
          ElMessage.success('订单已确认')
          this.loadOrders()
        } else {
          ElMessage.error('确认订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('确认订单失败')
        }
      }
    },
    
    async startService(orderId) {
      try {
        await ElMessageBox.confirm('开始提供服务？', '确认操作', {
          confirmButtonText: '开始',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        const response = await api.put(`/api/orders/${orderId}/status`, { status: 3 })
        if (response.success) {
          ElMessage.success('服务已开始')
          this.loadOrders()
        } else {
          ElMessage.error('更新状态失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('开始服务失败')
        }
      }
    },
    
    async completeOrder(orderId) {
      try {
        await ElMessageBox.confirm('确认完成此订单？', '确认操作', {
          confirmButtonText: '完成',
          cancelButtonText: '取消',
          type: 'success'
        })
        
        const response = await api.put(`/api/orders/${orderId}/status`, { status: 4 })
        if (response.success) {
          ElMessage.success('订单已完成')
          this.loadOrders()
        } else {
          ElMessage.error('完成订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('完成订单失败')
        }
      }
    },
    
    async cancelOrder(orderId) {
      try {
        await ElMessageBox.confirm('确认取消此订单？', '确认操作', {
          confirmButtonText: '取消订单',
          cancelButtonText: '返回',
          type: 'warning'
        })
        
        const response = await api.put(`/api/orders/${orderId}/status`, { status: 5 })
        if (response.success) {
          ElMessage.success('订单已取消')
          this.loadOrders()
        } else {
          ElMessage.error('取消订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消订单失败')
        }
      }
    },
    
    async createOrder() {
      if (!this.newOrder.serviceId || !this.newOrder.address || !this.newOrder.phone) {
        ElMessage.warning('请填写必要信息')
        return
      }
      
      try {
        const orderData = {
          ...this.newOrder,
          serviceTime: this.newOrder.serviceTime ? 
            this.newOrder.serviceTime.toISOString().split('T')[0] : null
        }
        
        const response = await api.post('/api/orders', orderData)
        if (response.success) {
          ElMessage.success('订单创建成功')
          this.showCreateDialog = false
          this.resetNewOrder()
          this.loadOrders()
        } else {
          ElMessage.error('创建订单失败')
        }
      } catch (error) {
        ElMessage.error('创建订单失败')
      }
    },
    
    reviewOrder(order) {
      this.reviewOrderData = order;
      this.showReviewDialog = true;
      this.reviewForm = {
        rating: 0,
        content: ''
      };
    },
    
    async submitReview() {
      if (!this.reviewForm.rating) {
        ElMessage.warning('请选择评分')
        return
      }
      
      try {
        const reviewData = {
          orderId: this.reviewOrderData.orderId,
          serviceId: this.reviewOrderData.serviceId,
          rating: this.reviewForm.rating,
          content: this.reviewForm.content
        }
        
        const response = await api.post('/api/reviews', reviewData)
        if (response.success) {
          ElMessage.success('评价提交成功')
          this.showReviewDialog = false
          this.loadOrders()
        } else {
          ElMessage.error('评价提交失败')
        }
      } catch (error) {
        ElMessage.error('提交评价失败')
      }
    },
    
    resetNewOrder() {
      this.newOrder = {
        serviceId: null,
        address: '',
        phone: '',
        serviceTime: null,
        requirements: ''
      }
    }
  }
}
</script>

<style scoped>
.order-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filters {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.filters .el-select {
  width: 150px;
}
</style> 